package com.gm.cards.domain;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Deck {

    public static Map<Integer, Card> cards = new HashMap<Integer, Card>();

    private List<Card> excludes;

    static {
	int count = 0;
	for (int i = 1; i <= 10; i++) {
	    for (int j = 1; j <= 4; j++) {
		cards.put(count, new Card(Number.valueOf(i), Suit.valueOf(j), count));
		count++;
	    }
	}
    }

    public Map<Integer, Card> getCards() {
	return cards;
    }

    public List<Card> getExcludes() {
	return excludes;
    }

    public void setExcludes(List<Card> excludes) {
	this.excludes = excludes;
    }

    public Card getRandomCard() {
	List<Card> availableCards = new ArrayList<Card>();
	availableCards.addAll(this.getCards().values());
	availableCards.removeAll(this.excludes);

	int position = new Double(Math.random() * availableCards.size()).intValue();
	Card card = availableCards.get(position);
	this.excludes.add(card);

	return card;
    }

    public void adjustWeights(Card turn) {
	Card card = getFirstNextNumber(turn);
	card.setWeight(11);
	for (int i = 0; i < 3; i++) {
	    card = getNext(card);
	    card.setWeight(12 + i);
	}
    }

    private static Card getNext(Card card) {
	if (card.getPositionOnDeck() == cards.size() - 1) {
	    return cards.get(0);
	}
	return cards.get(card.getPositionOnDeck() + 1);
    }

    private static Card getFirstNextNumber(Card card) {
	if (card.getNumber().equals(Number.KING)) {
	    return cards.get(0);
	}
	Card firstNextNumber = getNext(card);
	while (firstNextNumber.getNumber().equals(card.getNumber())) {
	    firstNextNumber = getNext(firstNextNumber);
	}
	return firstNextNumber;
    }
}
